package com.yanftch.stopcoding.request;

import com.yanftch.stopcoding.bean.HotBean;
import com.yanftch.stopcoding.cb.RequestCallBack;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class BaiduHotRequest implements Request {
    private static final String BAIDU_URL = "https://top.baidu.com/board?tab=realtime";

    public interface BaiduHotCallBack {
        void onSuccess(ArrayList<HotBean> list);

        void onError(Exception e);
    }

    @Override
    public void request(RequestCallBack callBack) {
        getBaiduHotList(new BaiduHotCallBack() {

            @Override
            public void onSuccess(ArrayList<HotBean> list) {
                if (callBack != null)
                    callBack.onSuccess(list);
            }

            @Override
            public void onError(Exception e) {
                if (callBack != null)
                    callBack.onError(e);
            }
        });
    }

    private void getBaiduHotList(@NotNull BaiduHotCallBack baiduHotCallBack) {

        try {
            Document doc = Jsoup.connect(BAIDU_URL).get();
            //标题
            Elements titles = doc.select(".c-single-text-ellipsis");
            //图片
            Elements imgs = doc.select(".category-wrap_iQLoo .index_1Ew5p").next("img");
            //内容
            Elements contents = doc.select(".hot-desc_1m_jR.large_nSuFU");
            //推荐图
            Elements urls = doc.select(".category-wrap_iQLoo a.img-wrapper_29V76");
            //热搜指数
            Elements levels = doc.select(".hot-index_1Bl1a");
            ArrayList<HotBean> list = new ArrayList<>();
            for (int i = 0; i < levels.size(); i++) {
                HotBean hotBean = new HotBean();
                hotBean.setTitle(titles.get(i).text().trim());
                hotBean.setUrl(urls.get(i).attr("href"));
                list.add(hotBean);
            }
            baiduHotCallBack.onSuccess(list);
        } catch (IOException e) {
            baiduHotCallBack.onError(new Exception("百度API路径变了，找插件开发者更新吧~"));
        } finally {
        }
    }

    public static void main(String[] args) {
//        getBaiduHotList(new BaiduHotCallBack() {
//            @Override
//            public void onSuccess(ArrayList<HotBean> list) {
//                for (HotBean bean : list) {
//                    System.out.println(bean);
//                }
//            }
//
//            @Override
//            public void onError(Exception e) {
//
//            }
//        });

    }
}
